package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.exception.CustomException;
import com.itheima.exception.SetmealException;
import com.itheima.pojo.*;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    SetmealService setmealService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    SetmealDishService setmealDishService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<IPage> findAll(Integer page, Integer pageSize, String name) {
        IPage<Setmeal> smPage = new Page<>(page, pageSize);
        IPage<SetmealDto> smPageDto = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);

        setmealService.page(smPage, lambdaQueryWrapper);

        List<Setmeal> setmeals = smPage.getRecords();
        List<SetmealDto> setmealDtoList = new ArrayList<>();
        for (Setmeal setmeal : setmeals) {
            SetmealDto setmealDto = new SetmealDto();

            BeanUtils.copyProperties(setmeal, setmealDto);

            Long categoryId = setmeal.getCategoryId();
            String categoryName = categoryService.getById(categoryId).getName();
            setmealDto.setCategoryName(categoryName);

            setmealDtoList.add(setmealDto);

        }
        smPageDto.setRecords(setmealDtoList);
        smPageDto.setTotal(smPage.getTotal());
        return R.success(smPageDto);
    }
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping
    public R list(@RequestBody SetmealDto setmealDto) {

        setmealService.add(setmealDto);

        return R.success("添加成功");

    }

    /**
     * 根据id查询数据用来回显
     */
    @GetMapping("/{id}")
    public R<SetmealDto> selectById(@PathVariable Long id) {
        //根据id查询setmeal中的数据
        Setmeal byId = setmealService.getById(id);

        SetmealDto setmealDto = new SetmealDto();
        //将数据拷贝setmealDto
        BeanUtils.copyProperties(byId, setmealDto);

        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
        //根据条件查询套餐下的所有菜品
        List<SetmealDish> list = setmealDishService.list(lambdaQueryWrapper);
        //放入dto中
        setmealDto.setSetmealDishes(list);

        return R.success(setmealDto);

    }

    /**
     * 修改套餐
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PutMapping
    public R<String> updateById(@RequestBody SetmealDto setmealDto) {
        //更新setmeal表
        setmealService.updateById(setmealDto);
        //获取setmeal id
        Long id = setmealDto.getId();
        //根据id查询菜品
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);

        //将此id下的菜品全部删除
        setmealDishService.remove(lambdaQueryWrapper);

        //获取前端传来的修改菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(id);
            setmealDishService.save(setmealDish);
        }

        return R.success("修改成功");

    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @DeleteMapping
    public R<String> deletById(Long[] ids) {
        if (ids.length == 0){
            throw new CustomException("多捞啊,请删除东西");
        }

        for (Long id : ids) {
            //根据ids查询需要删除的数据
            LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealLambdaQueryWrapper.eq(id!=0,Setmeal::getId, id);
            //判断这些要删除的数据中状态是否为0,为0就抛异常
            List<Setmeal> list = setmealService.list(setmealLambdaQueryWrapper);
            for (Setmeal setmeal : list) {
                if (setmeal.getStatus() == 1) {
                    throw new SetmealException("多捞啊");
                }
            }
            setmealService.removeById(id);
            //查询表中与id有关的数据
            LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
            setmealDishService.remove(dishLambdaQueryWrapper);

        }
        //redisTemplate.delete()
        return R.success("删除成功");
    }
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status,Long [] ids){
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("操作成功");

    }
   @Cacheable(value = "setmealCache",key ="#setmeal.categoryId + '_' + #setmeal.status",unless = "#result.data.size() == 0 ")
    @GetMapping("/list")
    public R  list(Setmeal setmeal){
        //String dishRedisId = "dish_" + setmeal.getCategoryId();
        //List<SetmealDto> setmealDtoList = (List<SetmealDto>) redisTemplate.opsForValue().get(dishRedisId);
        //if (setmealDtoList!=null){
        //    return R.success(setmealDtoList);
        //}

        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId())
                .eq(Setmeal::getStatus,1);
        //获取套餐分类下的套餐数据
        List<Setmeal> list = setmealService.list(lambdaQueryWrapper);

        List<SetmealDto> setmealDtoList = list.stream().map((item) ->{
            SetmealDto setmealDto = new SetmealDto();
            //拷贝数据
            BeanUtils.copyProperties(item,setmealDto);

            //获取分类名称
            Long categoryId = setmeal.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            setmealDto.setCategoryName(byId.getName());
            //查询套餐下的菜品
            LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,item.getId());
            List<SetmealDish> setmealDishList = setmealDishService.list(dishLambdaQueryWrapper);

            setmealDto.setSetmealDishes(setmealDishList);

            return setmealDto;

        }).collect(Collectors.toList());

        // redisTemplate.opsForValue().set(dishRedisId,setmealDtoList);


        return R.success(setmealDtoList);






    }

}
